import datetime
import json

from django.db import IntegrityError
from django.shortcuts import render
from django.http.response import HttpResponse
from administrator.models import Administrator
from django.core import serializers


# Create your views here.

def login(request):
    if request.method != "POST":
        return
    data = json.loads(request.body)
    if not data.get("id"):
        return HttpResponse("请输入编号")
    if not data.get("password"):
        return HttpResponse("请输入密码")
    try:
        user = Administrator.objects.filter(admin_number=data.get("id"), admin_password=data.get("password"))
        if not user:
            return HttpResponse('用户名或密码错误')
        return HttpResponse(json.loads(serializers.serialize("json", user)))
    except BaseException as e:
        print(e)
        return HttpResponse("查询错误")


def register(request):
    if request.method == "GET":
        return

    data = json.loads(request.body)
    try:
        # 生日格式为  yy-MM-dd
        birthday = datetime.datetime.strptime(
            data.get("birthday"), "%Y-%m-%d"
        )
        admin_person = Administrator.objects.create(
            admin_number=data.get("id"),
            admin_name=data.get("name"),
            admin_sex=data.get("sex"),
            admin_duty=data.get("duty"),
            admin_phone=data.get("telephone"),
            admin_password=data.get("password"),
            admin_birthday=birthday
        )
        admin_person.save()
        return HttpResponse("注册成功")
    except IntegrityError as i:
        print(i)
        return HttpResponse("账户已注册")
    except BaseException as e:
        print(e)
        return HttpResponse("注册失败")


def changePassword(request):
    if request.method == "GET":
        return
    data = json.loads(request.body)
    if not data.get("newPsd"):
        return HttpResponse("请输入编号")
    if not data.get("oldPsd"):
        return HttpResponse("请输入旧密码")
    if not data.get("newPsd"):
        return HttpResponse("请输入新密码")

    try:
        user = Administrator.objects.filter(admin_number=data.get("id"), admin_password=data.get("oldPsd"))
        user.update(admin_password=data.get("newPsd"))
        return HttpResponse("修改成功")
    except BaseException as e:
        print(e)
        return HttpResponse("修改失败")


def changeAdmin(request):
    if request.method != "POST":
        return
    data = json.loads(request.body)
    try:
        admin = Administrator.objects.filter(admin_number=data.get("id"))
        birthday = datetime.datetime.strptime(
            data.get("birthday"), "%Y-%m-%d"
        )
        admin.update(
            admin_name=data.get("name"),
            admin_sex=data.get("sex"),
            admin_phone=data.get("telephone"),
            admin_birthday=birthday,
            admin_duty=data.get("duty")
        )
        return HttpResponse("修改成功")
    except BaseException as e:
        print(e)
        return HttpResponse("修改失败")
